# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com


import urllib
from datetime import datetime
import zipfile
from StringIO import StringIO
 
    
def get_historical_prices(symbol, start_date, end_date):
    """

    Returns a nested list.
    """
    url = 'http://pitrading.com/free_eod_data/%s.zip' % symbol.upper()
    d = urllib.urlopen(url)
    z = zipfile.ZipFile(StringIO(d.read()))
    file = z.open(z.filelist[0].filename)
    header = file.readline().strip('\r\n').replace('"','')
    headings = header.split(',')
    dateIndex = headings.index('Date')
    priceIndex = headings.index('Close')
    returnData = []
    for line in file:
        data = line.strip('\r\n').split(',')
        try:
            date = datetime.date(datetime.strptime(data[dateIndex],'%m/%d/%Y'))
            price = float(data[priceIndex])
            if date >= start_date and date <= end_date:
                returnData.append([date, price])
        except:
            pass
    file.close()

    return returnData